<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>车站管理 - 铁路管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/admin/css/styles.css">
    <style>
        #app2 {
            display: flex;
            min-height: 100vh;
            width: 100%;
        }
    </style>
</head>
<body>

<div id="app2">
    <!-- 主内容区 -->
    <div class="main-content">

        <!-- 页面内容区域 -->
        <div id="page-content" style="padding: 0 20px;">
            <!-- 搜索和添加区域 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h3 class="card-title">车站查询</h3>
                </div>
                <div class="card-body">
                    <form class="form-row" @submit.prevent="search">
                        <div class="form-group col-3">
                            <label for="stationName">车站名称</label>
                            <input id="stationName" type="text" v-model="searchForm.stationName" class="form-control"
                                   placeholder="请输入车站名称">
                        </div>
                        <div class="form-group col-3">
                            <label for="province">所在省份</label>
                            <input id="province" type="text" v-model="searchForm.province" class="form-control"
                                   placeholder="请输入省份">
                        </div>
                        <div class="form-group col-4" style="display: flex; align-items: flex-end;">
                            <button type="button" @click="search" class="btn btn-primary" style="margin-right: 10px;">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                            <button type="button" @click="openModal('添加车站')" class="btn btn-success">
                                <i class="fas fa-plus"></i> 添加车站
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 数据表格区域 -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">车站列表</h3>
                </div>
                <div class="card-body">
                    <div class="table-container">
                        <table class="table">
                            <thead>
                            <tr>
                                <th>车站ID</th>
                                <th>车站名称</th>
                                <th>所在城市</th>
                                <th>所在省份</th>
                                <th>所属铁路局</th>
                                <th>联系电话</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr v-for="item in paginatedData" :key="item.stationId">
                                <td>{{ item.stationId }}</td>
                                <td>{{ item.stationName }}</td>
                                <td>{{ item.city || '-' }}</td>
                                <td>{{ item.province || '-' }}</td>
                                <td>{{ item.railwayBureauEntity && item.railwayBureauEntity.bureauName ? item.railwayBureauEntity.bureauName : '-' }}</td>
                                <td>{{ item.contactPhone || '-' }}</td>
                                <td>{{ item.createTime }}</td>
                                <td>
                                    <button @click="handleEdit(item)" class="btn btn-primary btn-sm">
                                        <i class="fas fa-edit"></i> 编辑
                                    </button>
                                    <button @click="handleDelete(item.stationId)" class="btn btn-danger btn-sm">
                                        <i class="fas fa-trash"></i> 删除
                                    </button>
                                </td>
                            </tr>
                            <tr v-if="paginatedData.length === 0">
                                <td colspan="7" style="text-align: center;">暂无数据</td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <!-- 分页区域 -->
                    <div class="pagination"
                         style="margin-top: 20px; display: flex; justify-content: center; align-items: center;">
                        <button class="btn btn-sm" :disabled="currentPage === 1" @click="prevPage">&laquo;</button>

                        <span class="page-info" style="margin: 0 10px;">
                            第 {{ startIndex + 1 }}-{{ endIndex }} 条，共 {{ totalItems }} 条
                        </span>

                        <div class="page-numbers" style="display: flex; margin: 0 10px;">
                            <button v-for="page in pages" :key="page"
                                    class="btn btn-sm"
                                    :class="{ 'btn-primary': page === currentPage }"
                                    @click="goToPage(page)">
                                {{ page }}
                            </button>
                        </div>

                        <button class="btn btn-sm" :disabled="currentPage === totalPages" @click="nextPage">&raquo;</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑模态框 -->
    <div v-if="isModalVisible" class="modal"
         style="position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4);">
        <div class="modal-content"
             style="background-color: #fefefe; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; max-width: 700px; border-radius: 8px;">
            <div class="modal-header" style="padding: 10px 0; border-bottom: 1px solid #ddd; margin-bottom: 20px;">
                <h3>{{ currentModalTitle }}</h3>
                <span class="close"
                      style="color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer;"
                      @click="closeModal">&times;</span>
            </div>

            <form @submit.prevent="saveData">
                <input type="hidden" v-model="formData.stationId">
                <div class="form-row">
                    <div class="form-group col-6">
                        <label for="station_name">车站名称 <span style="color: red;">*</span></label>
                        <input id="station_name" type="text" v-model="formData.stationName" class="form-control" required
                               placeholder="请输入车站名称">
                    </div>
                    <div class="form-group col-6">
                        <label for="city">所在城市 <span style="color: red;">*</span></label>
                        <input type="text" v-model="formData.city" class="form-control" required
                               placeholder="请输入所在城市">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-6">
                        <label for="province">所在省份 <span style="color: red;">*</span></label>
                        <input type="text" v-model="formData.province" class="form-control" required
                               placeholder="请输入所在省份">
                    </div>
                    <div class="form-group col-6">
                        <label for="railway_bureau_id">所属铁路局</label>
                        <select v-model="formData.railwayBureauId" class="form-control">
                            <option value="">请选择铁路局</option>
                            <option v-for="bureau in bureauList" :key="bureau.id" :value="bureau.id">
                                {{ bureau.bureauName }}
                            </option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-6">
                        <label for="contact_phone">联系电话</label>
                        <input type="text" v-model="formData.contactPhone" class="form-control"
                               placeholder="请输入联系电话">
                    </div>
                    <div class="form-group col-3">
                        <label for="globalX">经度</label>
                        <input type="number" v-model="formData.globalX" class="form-control"
                               placeholder="请输入经度" step="0.000001">
                    </div>
                    <div class="form-group col-3">
                        <label for="globalY">纬度</label>
                        <input type="number" v-model="formData.globalY" class="form-control"
                               placeholder="请输入纬度" step="0.000001">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-12">
                        <label for="address">详细地址</label>
                        <textarea v-model="formData.address" class="form-control" rows="3"
                                  placeholder="请输入详细地址（可选）"></textarea>
                    </div>
                </div>
                <div class="form-group" style="margin-top: 20px;">
                    <button type="submit" class="btn btn-primary" style="margin-right: 10px;">保存
                    </button>
                    <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
                </div>
            </form>
        </div>
    </div>

</div>
<script src="/admin/js/auth.js"></script>
<script src="/admin/js/jquery-3.6.0.js"></script>
<script src="/admin/js/vue.js"></script>
<script src="/admin/js/load-navbar.js"></script>
<script src="/admin/js/user-info.js"></script>
<script src="/admin/js/axios.js"></script>
<script src="/admin/js/config.js"></script>

<script>
    new Vue({
        el: '#app2',
        data: {
            isModalVisible: false,
            currentModalTitle: '',
            searchForm: {
                stationName: '',
                province: ''
            },
            formData: {
                stationId: '',
                stationName: '',
                city: '',
                province: '',
                railwayBureauId: '',
                address: '',
                contactPhone: '',
                globalX: '', // 添加经度字段
                globalY: ''   // 添加纬度字段
            },
            tableData: [],
            bureauList: [], // 铁路局列表，用于下拉选择

            // 分页相关数据
            currentPage: 1,
            pageSize: 8,
            totalItems: 0,
            // 控制是否使用前端分页
            // 如果后端已进行分页，设置为false；如果后端返回全部数据，设置为true
            useFrontendPagination: false,

            userName: ''
        },
        computed: {
            // 计算总页数
            totalPages() {
                return Math.ceil(this.totalItems / this.pageSize);
            },

            // 当前页显示的数据
            paginatedData() {
                // 如果使用前端分页，则对全部数据进行分页
                // 否则，直接使用后端返回的当前页数据
                if (this.useFrontendPagination) {
                    const start = (this.currentPage - 1) * this.pageSize;
                    const end = start + this.pageSize;
                    return this.tableData.slice(start, end);
                } else {
                    // 后端已分页的情况下，直接返回当前页数据
                    return this.tableData;
                }
            },

            // 显示的页码范围
            pages() {
                const pages = [];
                const maxVisiblePages = 5; // 最多显示5个页码

                let startPage = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2));
                let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);

                if (endPage - startPage < maxVisiblePages - 1) {
                    startPage = Math.max(1, endPage - maxVisiblePages + 1);
                }

                for (let i = startPage; i <= endPage; i++) {
                    pages.push(i);
                }

                return pages;
            },

            // 当前页起始索引
            startIndex() {
                return (this.currentPage - 1) * this.pageSize;
            },

            // 当前页结束索引
            endIndex() {
                const end = this.startIndex + this.pageSize;
                return Math.min(end, this.totalItems);
            }
        },
        methods: {
            search() {
                this.currentPage = 1; // 搜索时重置到第一页
                this.loadData();
            },

            openModal(title, data = {}) {
                this.currentModalTitle = title;
                this.formData = {...data};
                this.isModalVisible = true;
            },

            closeModal() {
                this.isModalVisible = false;
                this.resetForm();
            },

            resetForm() {
                this.formData = {
                    stationId: '',
                    stationName: '',
                    city: '',
                    province: '',
                    railwayBureauId: '',
                    address: '',
                    contactPhone: '',
                    globalX: '', // 初始化经度
                    globalY: ''   // 初始化纬度
                };
            },

            saveData() {
                if (!this.formData.stationName || !this.formData.city || !this.formData.province) {
                    alert('车站名称、城市和省份为必填项');
                    return;
                }
                console.log('保存数据:', this.formData);

                axios.post("/admin/station_manage/save", this.formData)
                    .then(resp => {
                        if (resp.code === 200) {
                            alert(resp.data.message);
                            // 保存后重新加载数据
                            this.loadData();
                        } else {
                            alert(resp.data.message);
                            // 保存后重新加载数据
                            this.loadData();
                        }
                    })
                this.closeModal();
            },

         handleEdit(item) {
    // 处理编辑时的数据转换
    // 如果后端返回了railwayBureauEntity对象，提取railwayBureauId
    const editData = {
        ...item,
        // 优先使用item中的railwayBureauId，如果没有则检查railwayBureauEntity对象
        railwayBureauId: item.railwayBureauId !== undefined ? item.railwayBureauId :
                      (item.railwayBureauEntity && item.railwayBureauEntity.id ? item.railwayBureauEntity.id : '')
    };
    this.openModal('编辑车站', editData);
},

            handleDelete(id) {
                if (confirm(`确定要删除ID为 ${id} 的车站吗？`)) {
                    console.log('删除ID:', id);

                    axios.delete("/admin/station_manage/delete/" + id)
                        .then(resp => {
                            if (resp.code === 200) {
                                alert(resp.data.message)
                                this.loadData();
                            } else {
                                alert(resp.data.message)
                                this.loadData();
                            }
                        })

                    // 删除后重新加载数据
                    this.loadData();
                }
            },

            // 分页方法
            prevPage() {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.loadData();
                }
            },

            nextPage() {
                if (this.currentPage < this.totalPages) {
                    this.currentPage++;
                    this.loadData();
                }
            },

            goToPage(page) {
                this.currentPage = page;
                this.loadData();
            },

            // 加载数据
            loadData() {
                // 实际环境中使用的API请求
                axios.get("/admin/station_manage/getList", {
                    params: {
                        page: this.currentPage,
                        pageSize: this.pageSize,
                        stationName: this.searchForm.stationName || '',
                        province: this.searchForm.province || ''
                    }
                })
                    .then(resp => {
                        console.log('请求参数:', {currentPage: this.currentPage, pageSize: this.pageSize});
                        console.log('响应数据:', resp.data);

                        if (resp.data.code === 200) {
                            // 确保数据格式正确
                            const listData = resp.data.data.list;
                            const totalCount = resp.data.data.total;

                            this.tableData = listData;
                            this.totalItems = totalCount;
                        } else {
                            alert("加载数据失败: " + resp.data.message);
                            // 出错时设置空数据，避免显示错误数据
                            this.tableData = [];
                            this.totalItems = 0;
                        }
                    })
                    .catch(error => {
                        console.error("请求错误:", error);
                        alert("加载数据失败，请检查网络连接");
                        // 出错时设置空数据
                        this.tableData = [];
                        this.totalItems = 0;
                    });
            },

            // 加载铁路局列表，用于下拉选择
            loadBureauList() {
                // 根据新的StationEntity实体类，应该请求铁路局列表
                // 这里调整API路径为更合理的接口
                axios.get("/admin/station_manage/getAllBureauList")
                    .then(resp => {
                        if (resp.data.code === 200) {
                            this.bureauList = resp.data.data;
                        } else {
                            console.error("加载铁路局列表失败:", resp.data.message);
                        }
                    })
                    .catch(error => {
                        console.error("请求错误:", error);
                    });
            }
        },
        mounted() {
            this.loadData();
            this.loadBureauList(); // 加载铁路局列表用于下拉选择
        },
        created() {
            // 从localStorage获取用户名
            this.userName = localStorage.getItem('savedAdminName') || '用户';

            // 检查是否已登录（是否有token）
            const token = localStorage.getItem('saToken');
            if (!token) {
                // 如果没有token，跳转回登录页
                window.location.href = "/admin/login.html";
            }
        }
    });
</script>
</body>
</html>
